package com.taobao.job;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: caoling
 * Date: 11-3-11
 * Time: 11:31
 * To change this template use File | Settings | File Templates.
 */
public class PVCounter {
    public static final String divider = "\001";
    public static final String space = " ";
    private static final LongWritable one = new LongWritable(1L);

    public static void main(String[] args)
            throws Exception {
        JobConf conf = new JobConf(PVCounter.class);
        conf.setJobName("count pv");
        conf.setOutputKeyClass(LongWritable.class);
        conf.setOutputValueClass(LongWritable.class);

        conf.setMapperClass(Map.class);
        conf.setReducerClass(Reduce.class);
        conf.setMapOutputKeyClass(LongWritable.class);
        conf.setMapOutputValueClass(Text.class);

        conf.setInputFormat(TextInputFormat.class);
        conf.setOutputFormat(TextOutputFormat.class);

        String resultPath = "pv" + System.currentTimeMillis();
        FileInputFormat.setInputPaths(conf, new Path[]{new Path("data")});
        FileOutputFormat.setOutputPath(conf, new Path(resultPath));

        JobClient.runJob(conf);
    }

    public static class Reduce extends MapReduceBase
            implements Reducer<LongWritable, Text, LongWritable, LongWritable> {
        public void reduce(LongWritable key, Iterator<Text> values, OutputCollector<LongWritable, LongWritable> output, Reporter reporter)
                throws IOException {
            Set valueSet = new HashSet();

            while (values.hasNext()) {
                valueSet.add(((Text) values.next()).toString());
            }
            output.collect(key, new LongWritable(valueSet.size()));
        }
    }

    public static class Map extends MapReduceBase
            implements Mapper<LongWritable, Text, LongWritable, Text> {
        public void map(LongWritable key, Text text, OutputCollector<LongWritable, Text> output, Reporter reporter)
                throws IOException {
            String line = text.toString();
            String[] contents = line.split("\001");
            Long catId = Long.valueOf(contents[19]);
            String pvString = contents[10];
            if (StringUtils.isNotEmpty(pvString)) {
                String[] pvs = pvString.split(";");
                for (String pv : pvs)
                    output.collect(new LongWritable(catId.longValue()), new Text(pv));
            }
        }
    }
}
